<template>
    <el-card shadow="never" class="card-single">
        <el-tabs v-model="activeName" @tab-click="tabClick">
            <el-tab-pane label="院审核权限配置" :name="college"></el-tab-pane>
            <el-tab-pane label="校审核权限配置" :name="school"></el-tab-pane>
            <el-tab-pane label="编辑权限配置" :name="editConfig"></el-tab-pane>
        </el-tabs>
        <div class="content" v-if="activeName != 'editConfig'">
            <div class="config-left">
                <el-input
                    placeholder="输入用户组名称搜索"
                    style="width:calc(100% - 40px);margin:20px"
                    @keyup.enter.native="searchRole"
                    v-model="filterText"
                >
                    <i
                        class="el-icon-search"
                        slot="suffix"
                        style="margin-top:10px;cursor:pointer"
                        @click="searchRole"
                    ></i>
                </el-input>
                <el-radio-group v-model="all" class="radio-gp">
                    <el-radio-button :label="false">已配置</el-radio-button>
                    <el-radio-button :label="true">全部</el-radio-button>
                </el-radio-group>
                <div class="tree-zone">
                    <el-tree
                        ref="tree"
                        :expand-on-click-node="false"
                        :highlight-current="true"
                        :data="roles"
                        :props="defaultProps"
                        @node-expand="handleRoleClick"
                        @node-click="nodeClick"
                    ></el-tree>
                </div>
            </div>
            <div class="config-right">
                <div class="top" v-if="selectItem">
                    <div class="title">字段权限</div>
                    <div class="reset">
                        <el-button @click="reset">{{$t("message.reset")}}</el-button>
                        <el-button type="primary" @click="saveConfig">{{$t('message.save')}}</el-button>
                    </div>
                </div>
                <div class="check-list">
                    <table
                        style="width:100%"
                        cellspacing="0"
                        cellpadding="0"
                        border="1"
                        class="field-table"
                    >
                        <tr v-for="(item,i) in fields" :key="i" :class="item.isType?'is-type':null">
                            <td v-for="(f,j) in item.children" :key="j" :colspan="item.isType?4:1">
                                <el-checkbox
                                    v-if="f.name"
                                    :indeterminate="f.indeterminate"
                                    v-model="f.checked"
                                    :title="f.name"
                                    @change="changeCheck(item,f)"
                                >{{f.name}}</el-checkbox>
                            </td>
                        </tr>
                    </table>
                </div>
            </div>
            <div style="clear:both"></div>
        </div>
        <div class="content" v-if="activeName === 'editConfig'" style="height:800px;overflow:scroll;padding-bottom:70px">
            <editConfig/>
        </div>
        <el-dialog :title="$t('message.prompt')" width="450px" :visible.sync="showDialog">
            <div>您的当前操作尚未保存，是否确认切换页签？</div>
            <div class="float-right" style="margin:25px 0 0 0">
                <el-button @click="showDialog=false">{{$t("message.cancel")}}</el-button>
                <el-button @click="saveConfig(true)" type="primary">{{$t("message.save")}}</el-button>
                <el-button @click="confirm" type="primary">{{$t("message.confirm")}}</el-button>
            </div>
            <div style="clear:both"></div>
        </el-dialog>
    </el-card>
     
</template>
<script>
import {
    getApproRoles,
    getApproUser,
    getApproFields,
    addFieldRoleConfig,
    getAllApproFields
} from "common/src/api/studentinfo";
import editConfig from './editConfig'
const configType = {
    COLLEGE: 7,
    SCHOOL: 8,
    EDITCONFIG: 'editConfig'
};
export default {
    name: "ApproveAuthorityConfig",
    components: { editConfig },
    data() {
        return {
            college: configType.COLLEGE,
            school: configType.SCHOOL,
            editConfig: configType.EDITCONFIG,
            activeName: configType.COLLEGE, //值为college或school
            tmpActiveName: configType.COLLEGE,
            all: false, //全部或已配置
            selectItem: null,
            roles: [],
            filterText: null,
            keyword: null,
            defaultProps: {
                children: "children",
                label: "roleName"
            },
            fields: [],
            rawFields: [],
            showDialog: false,
            currentRoleId: null,
        };
    },
    mounted() {
        this.getRoleData();
    },
    watch: {
        all: function(val) {
            this.getRoleData();
        },
        tmpActiveName: function(val) {
            this.getRoleData();
            this.fields = [];
            this.rawFields = [];
        }
    },
    
    methods: {
        tabClick() {
            if (this.activeName == this.tmpActiveName) {
                return;
            }
            if(this.activeName !== 'editConfig') {
                if (this.isChanged()) {
                this.showDialog = true;
                //阻止切换tab,判断配置是否存在改变(element-ui2.3.9不支持tab的钩子函数)
                document.getElementById("tab-" + this.tmpActiveName).click();
                } else {
                    this.tmpActiveName = this.activeName;
                }
            }
        },
        reset() {
            this.fields = _.cloneDeep(this.rawFields);
        },
        saveConfig(isToggle) {
            let postArray = [];
            this.fields
                .filter(field => !field.isType)
                .forEach(field => {
                    field.children.forEach(f => {
                        if (f.item && f.item.isChecked == null && f.checked) {
                            f.item.roleId = this.selectItem.roleId;
                            if (this.currentRoleId == null) {
                                f.item.userId = this.selectItem.userId;
                            }
                            f.item.isChecked = 1;
                            postArray.push(f.item);
                        } else if (f.item && f.item.isChecked != null) {
                            let chk = f.checked ? 1 : 0;
                            f.item.roleId = this.selectItem.roleId;
                            if (this.currentRoleId == null) {
                                f.item.userId = this.selectItem.userId;
                            }
                            f.item.isChecked = chk;
                            postArray.push(f.item);
                        }
                    });
                });
            let postData = {
                stuFieldRoleConfigs: postArray
            };
            if (this.currentRoleId != null) {
                postData.type = this.all ? 0 : 1;
            }
            if (postData.stuFieldRoleConfigs.length > 0) {
                addFieldRoleConfig(postData).then(res => {
                    if (res.code == 200) {
                        this.$message({
                            message: "保存成功",
                            type: "success"
                        });
                        this.fields
                            .filter(field => !field.isType)
                            .forEach(field => {
                                field.children.forEach(f => {
                                    f.changed = null;
                                });
                            });
                        if (isToggle == true) {
                            this.closeDialogAndToggle();
                        } else {
                            this.rawFields = _.cloneDeep(this.fields);
                        }
                    }
                });
            } else {
                this.$message({
                    message: "请设置字段权限",
                    type: "info"
                });
            }
            
        },
        searchRole() {
            if (this.keyword != this.filterText) {
                this.keyword = this.filterText;
                this.getRoleData();
            }
        },
        //点击角色加载人员
        handleRoleClick(item) {
            if (item.children.length > 0 && item.children[0] != 0) {
                return;
            }
            getApproUser(item.roleId, this.all ? 0 : 1, this.activeName).then(
                res => {
                    if (res.code == 200) {
                        item.children = res.data.map(user => {
                            user.roleName =
                                user.userName + "(" + user.userId + ")";
                            user.leaf = true;
                            user.roleId = item.roleId;
                            return user;
                        });
                    }
                }
            );
        },
        //点击人员加载字段列表
        nodeClick(item) {
            if (item.leaf) {
                this.selectItem = item;
                this.currentRoleId = null;
                this.getUserFields(item);
            } else {
                this.selectItem = item;
                this.currentRoleId = item.roleId;
                getAllApproFields(this.activeName).then(res => {
                    if (res.code == 200) {
                        this.initFields(res);
                    }
                });
            }
        },
        //查询角色
        getRoleData() {
            this.selectItem = null;
            this.fields = [];
            this.rawFields = [];
            let query = {
                roleName: this.keyword,
                type: this.all ? 0 : 1,
                configId: this.activeName
            };
            getApproRoles(query).then(res => {
                if (res.code == 200) {
                    res.data.forEach(role => {
                        role.children = [0]; //默认节点值
                    });
                    this.roles = res.data;
                }
            });
        },
        getUserFields(item) {
            if (!item) return;
            let query = {
                configId: this.activeName,
                roleId: item.roleId,
                userId: item.userId
            };
            getApproFields(query).then(res => {
                if (res.code == 200) {
                    this.initFields(res);
                }
            });
        },
        initFields(res) {
            let fieldClasses = [];
            res.data.forEach(item => {
                if (
                    fieldClasses.indexOf(item.fieldClass) == -1 &&
                    item.fieldClass
                ) {
                    fieldClasses.push(item.fieldClass);
                }
            });
            let fields = [];
            let i = 0;
            fieldClasses.forEach(fieldClass => {
                let id = ++i;
                fields.push({
                    seq: id,
                    isType: true,
                    children: [
                        {
                            name: fieldClass,
                            checked: false,
                            indeterminate: false
                        }
                    ]
                });
                let columns = res.data.filter(
                    item => item.fieldClass == fieldClass
                );
                if (columns.length > 0) {
                    let array = [];
                    for (let j = 1; j <= columns.length; j++) {
                        array.push({
                            name: columns[j - 1].fieldName,
                            checked: columns[j - 1].isChecked ? true : false,
                            item: columns[j - 1]
                        });
                        if (j % 4 == 0) {
                            fields.push({
                                seq: ++i,
                                isType: false,
                                children: array,
                                pid: id
                            });
                            array = [];
                        }
                    }
                    if (columns.length % 4) {
                        let appendCount = 4 - array.length;
                        for (let j = 0; j < appendCount; j++) {
                            array.push({});
                        }
                        fields.push({
                            seq: ++i,
                            isType: false,
                            children: array,
                            pid: id
                        });
                    }
                }
            });
            this.fields = fields;
            this.fields.forEach(row => {
                if (row.isType) {
                    this.updateParentChk(row.seq);
                }
            });
            this.rawFields = _.cloneDeep(fields);
        },
        changeCheck(obj, field) {
            if (obj.isType) {
                field.indeterminate = false;
                this.fields
                    .filter(item => item.pid == obj.seq)
                    .forEach(row => {
                        row.children.forEach(n => {
                            if (n.checked != field.checked) {
                                n.checked = field.checked;
                                this.setItemChangeState(n);
                            }
                        });
                    });
            } else {
                this.setItemChangeState(field);
                this.updateParentChk(obj.pid);
            }
        },
        //更新父复选框状态
        updateParentChk(pid) {
            let rows = this.fields.filter(item => item.pid == pid);
            parent = this.fields.find(item => item.seq == pid);
            let columns = rows.reduce(
                (result, row) => result.concat(row.children),
                []
            );
            columns = columns.filter(column => column.item);
            if (columns.every(n => n.checked)) {
                parent.children[0].checked = true;
                parent.children[0].indeterminate = false;
            } else if (columns.every(n => !n.checked)) {
                parent.children[0].checked = false;
                parent.children[0].indeterminate = false;
            } else {
                parent.children[0].indeterminate = true;
            }
        },
        setItemChangeState(item) {
            item.changed = item.changed ? 0 : 1;
        },
        //判断是否checkbox是否改变,排除字段类型行
        isChanged() {
            let changed = false;
            this.fields
                .filter(field => !field.isType)
                .forEach(field => {
                    field.children.forEach(f => {
                        if (f.changed) {
                            changed = true;
                        }
                    });
                });
            return changed;
        },
        confirm() {
            this.closeDialogAndToggle();
        },
        closeDialogAndToggle() {
            this.showDialog = false;
            this.activeName =
                this.activeName == configType.COLLEGE
                    ? configType.SCHOOL
                    : configType.COLLEGE;
            this.tmpActiveName = this.activeName;
        }
    }
};
</script>
<style lang="scss" scoped>
.content {
    margin-top: -15px;
    height: calc(100% - 35px);
}
.config-left {
    width: 25%;
    float: left;
    border: 2px solid #f0f2f5;
    border-top: 0;
    border-right: 0;
    height: 100%;
    border-top: 0;
    .radio-gp {
        margin-bottom: 20px;
        margin-left: 20px;
    }
    .tree-zone {
        height: calc(100% - 130px);
        overflow: auto;
    }
}
.config-right {
    width: 75%;
    float: right;
    border: 2px solid #f0f2f5;
    height: 100%;
    border-top: 0;
    padding: 10px;
    .top {
        margin: 10px;
        overflow: auto;
        & > div:first-child {
            float: left;
            font-size: 16px;
            line-height: 32px;
        }
        & > div:last-child {
            float: right;
        }
    }
    .check-list {
        overflow: auto;
        height: calc(100% - 52px);
    }
    .field-table {
        table-layout: fixed;
        border-collapse: collapse;
        border: 1px solid #d2d4d6;
        tr.is-type {
            background: #f5f7f9;
        }
        tr td {
            line-height: 32px;
            padding-left: 10px;
            border-collapse: collapse;
            border: 1px solid #d2d4d6;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
    }
}
</style>
